package com.camel.iamhi.controller;

import com.camel.iamhi.base.BaseModel;
import com.camel.iamhi.base.Page;
import com.camel.iamhi.base.PageQuery;
import com.camel.iamhi.entities.AjaxResult;
import com.camel.iamhi.entities.IParams;
import com.camel.iamhi.enums.EntityStatus;
import com.camel.iamhi.model.SysUser;
import com.camel.iamhi.service.BaseService;
import org.springframework.ui.Model;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

public abstract class BaseController<T extends BaseModel> {


    @GetMapping
    public String index(Model model, @RequestHeader(value = "X-Requested-With", required = false) String requestedWith) {
        model.addAttribute("pageTitle", moduleName());
        // 如果是 Ajax 请求（局部刷新），仅返回主体片段
        if (!"XMLHttpRequest".equals(requestedWith)) {
            return "full";
        }
        return indexPagePath();
    }

    @PostMapping("/page")
    public @ResponseBody AjaxResult page(@RequestBody IParams params) {
        Page<T> page = getService().page(params);
        return AjaxResult.success(page);
    }

    @PostMapping("/list")
    public @ResponseBody AjaxResult list(@RequestBody IParams params) {
        return AjaxResult.success(getService().selectList(params));
    }

    @PostMapping("/save")
    public @ResponseBody AjaxResult save(@RequestBody T entity) {
        entity.setStatus(EntityStatus.NORMAL.getCode());
        entity.setCreator(1L);
        entity.setCreateAt(new Date());
        if(!ObjectUtils.isEmpty(getService().save(entity))) {
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }

    @PostMapping("/update")
    public @ResponseBody AjaxResult update(@RequestBody T entity) {
        entity.setCreateAt(new Date());
        entity.setCreator(1L);
        if(!ObjectUtils.isEmpty(getService().save(entity))) {
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }

    @DeleteMapping("/delete/{id}")
    public @ResponseBody AjaxResult delete(@PathVariable Long id) {
        getService().delete(id);
        return AjaxResult.success();
    }



    abstract String indexPagePath();

    abstract String moduleName();

    abstract BaseService<T> getService();
}
